import React from 'react'
import {Upload, Icon, message} from 'antd';
import './index.css'
import {httpUrl} from '../../utils/config'

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isLt2M;
}

class Avatar extends React.Component {
    state = {
        loading: false,
        commodity_image_thum:''
    };
    getImg = (e) => {
        this.props.getImg(e,this.props.id)
    }
    componentDidMount() {
        this.setState({
            imageUrl:this.props.commodity_image_thum
        })
    }

    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({loading: true});
            return;
        }
        if (info.file.status === 'done') {
            if(info.file.response.code < 400) {
                let commodity_image_thum = info.file.response.data.url
                this.getImg(commodity_image_thum)
                this.setState({
                    commodity_image_thum
                })
            }
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (imageUrl) => {
                    this.setState({
                        imageUrl,
                        loading: false
                    })
                }
            );
        }
    };

    render() {
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'}/>
                <div className="ant-upload-text">请添加图片</div>
            </div>
        );
        const {imageUrl} = this.state;
        return (
            <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader1"
                showUploadList={false}
                action={httpUrl+"/imageFileObject?prefix=tgshop_commodity"}
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
            >
                {imageUrl ? <img width={100} height={100} src={imageUrl} alt="avatar"/> : uploadButton}
            </Upload>
        );
    }
}

export default Avatar;
